package com.example.demo.service.impl;

import com.example.demo.dao.IOrderDao;
import com.example.demo.model.Order;
import com.example.demo.recursive.tasks.InsertOrderTask;
import com.example.demo.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;

/**
 * @author tuf
 * @description 针对表【order】的数据库操作Service实现
 * @createDate 2022-03-05 10:56:02
 */
@Service
public class OrderServiceImpl implements OrderService {
    private static final Logger LOG = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Autowired
    private IOrderDao orderDao;

    @Override
    public int batchInsert() {
        //随机生成Order对象
        List<Order> orders = new ArrayList<>();
        LOG.info("单线程联机插入10000条数据开始---");
        for (int i = 0; i < 1000; i++) {
            orders.add(new Order(i + "", new Date()));
        }
        long begin = System.currentTimeMillis();
        int i = orderDao.bathcInsertOrder(orders);
        long now = System.currentTimeMillis();
        LOG.info("单线程联机插入10000条数据结束---耗时：{} 毫秒", now - begin);
        return i;
    }

    @Override
    public int batchInsertByForkJoin() throws ExecutionException, InterruptedException {
        List<Order> orders = new ArrayList<>();
        LOG.info("fork_join插入10000条数据开始---");
        long begin = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            orders.add(new Order(i + "", new Date()));
        }
        ForkJoinPool forkJoinPool = new ForkJoinPool(4);
        ForkJoinTask<Integer> submit = forkJoinPool.submit(new InsertOrderTask(0, orders.size(), orders, orderDao));
        long now = System.currentTimeMillis();
        LOG.info("fork_join插入10000条数据结束---耗时：{} 毫秒", now - begin);
        return submit.get();
    }
}
